package com.zhangfb95.crosschain.infra.util;

import io.netty.handler.ssl.SslContext;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;

/**
 * @author zhangfubing
 * @since 2023/12/26
 */
public class StdCertUtil {

    public static PrivateKey toPrivateKey(String content) {
        try {
            Method toPrivateKeyMethod = SslContext.class.getDeclaredMethod(
                    "toPrivateKey", InputStream.class, String.class);
            toPrivateKeyMethod.setAccessible(true);
            Object[] args = {new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)), null};
            return (PrivateKey) toPrivateKeyMethod.invoke(null, args);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

    public static X509Certificate[] toX509Certificates(String content) {
        try {
            Method toX509CertificatesMethod = SslContext.class.getDeclaredMethod(
                    "toX509Certificates", InputStream.class);
            toX509CertificatesMethod.setAccessible(true);
            Object[] args = {new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8))};
            return (X509Certificate[]) toX509CertificatesMethod.invoke(null, args);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }
}